//
//  ChartViewController.m
//  Futures
//
//  Created by Cheng on 2017/6/21.
//  Copyright © 2017年 Cheng. All rights reserved.
//


#import "ChartViewController.h"
#import "PageTitleView.h"
#import "PageContentView.h"
#import "LightningViewController.h"
#import "TimeViewController.h"
#import "KlineViewController.h"
#import "MarketViewController.h"
#import "BuyOrderViewController.h"
#import "ZFDropDown.h"
#import "ChartViewModel.h"
#import "QuickOrderModel.h"
#import "OrderViewModel.h"
#import "MineViewModel.h"
#import "TransacionViewModel.h"
#import "HoldingModel.h"

#define kPageTitleViewH 36
#define kGCDTimeName @"GetUserInfo"

@interface ChartViewController () <PageTitleViewDelegate,PageContentViewDelegate,ZFDropDownDelegate>{
    NSArray *_klineArray; // K线标题数组
    ZFDropDown *_dropDown;  // 下拉列表
    NSTimer *mTimer;
    QuoteModel *_quoteModel;
    BOOL isEnableTimer;
    HoldingModel *_currentModel;
}


@property (weak, nonatomic) IBOutlet UIView *indicatorView;

@property (weak, nonatomic) IBOutlet UILabel *buySellDirection;

@property (weak, nonatomic) IBOutlet UILabel *profit;

@property (strong,nonatomic) PageTitleView *pageTitleView;

@property (strong,nonatomic) PageContentView *pageContentView;

@property (weak, nonatomic) IBOutlet UIView *loginView;

@property (weak, nonatomic) IBOutlet UIView *orderDetailView;

@property (weak, nonatomic) IBOutlet UILabel *buyPrice;

@property (weak, nonatomic) IBOutlet UILabel *sellPrice;

@property (weak, nonatomic) IBOutlet UILabel *buyVolume;

@property (weak, nonatomic) IBOutlet UILabel *sellVolume;

@property (weak, nonatomic) IBOutlet UIView *buyProgress;

@property (weak, nonatomic) IBOutlet UIView *sellProgress;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buyViewWidth;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sellViewWidth;

@property (weak, nonatomic) IBOutlet UILabel *lastPrice;

@property (weak, nonatomic) IBOutlet UILabel *change;

@property (weak, nonatomic) IBOutlet UILabel *changeRate;


@end

@implementation ChartViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    self.tabBarController.title = [Global shareInstance].quoteModel.Symbolname;
    // 在navigation里嵌套了tabbarcontoller
    self.tabBarController.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highlightedIcon:nil target:self action:@selector(back)];
}

- (void)viewDidLayoutSubviews{ // 在这里计算size才是准确的,但是会重复调用，只在第一次启动调用
    [super viewDidLayoutSubviews];
    
    if (self.childViewControllers.count == 4) return;
    
    MYLog(@"redraw subviews");
    
    [self addPageContentView];
    
    [self addPageTitleView:@"K线图"];
    
    [self didSelectTitleView:self.pageTitleView index:1];
    
    [self didScrollPageContentView:self.pageContentView sourceIndex:1 targetIndex:1 progress:0];
    
    [self addKlineDrop];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //去除导航栏下方的横线
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init]
                                                  forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    // 登录后隐藏登录按钮
    self.loginView.hidden = GLOBAL_INSTANCE.user;
    
    [self startTimer];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self stopTimer];
    
    isEnableTimer = NO;
    
    if ([[JX_GCDTimerManager sharedInstance] existTimer:kGCDTimeName]) {
        [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:kGCDTimeName];
    }
}

- (void)startTimer // 30秒刷一次
{
    if (mTimer == nil) { // 30秒刷一次
        mTimer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1.0f target:self selector:@selector(processEvent) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:mTimer forMode:NSDefaultRunLoopMode];
        
    }
}

- (void)stopTimer
{
    [mTimer invalidate];
    mTimer = nil;
    
}

- (void)processEvent{
    [ChartViewModel requestQuoteWithSymbol:GLOBAL_INSTANCE.quoteModel.Symbol exchange:GLOBAL_INSTANCE.quoteModel.Exchange block:^(id obj) {
        _quoteModel = obj;
        [self updateUI];
    }];
    
    if (GLOBAL_ISLOGIN && isEnableTimer != YES) {
        
        //            __weak typeof(self) weakSelf = self;
        [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:kGCDTimeName timeInterval:10 queue:nil repeats:YES actionOption:AbandonPreviousAction action:^{
            MYLog(@"GCD Timer Event");
            __weak typeof(self) weakSelf = self;
            [TransacionViewModel requestHoldingWithBlck:^(id obj) {
                NSArray *holdingArray = obj;
                for (HoldingModel *model in holdingArray) {
                    if ([model.Symbol isEqualToString:GLOBAL_INSTANCE.quoteModel.Symbol]){
                        _currentModel = model;
                        [weakSelf updateUIWithHoldingModel]; // 记录当前的持仓单模型数据
                    }
                }
            }];
            
            [TransacionViewModel requestCloseOderWithBlck:^(id obj) {
                
            }];
            
            [MineViewModel requestAccountInfoWithBlock:^(id obj) {
                
            }];
        }];
        
        isEnableTimer = YES;
        
    }
}

- (void)updateUIWithHoldingModel{
    if ([_currentModel.BuySell containsString:@"买"]) {
        self.buySellDirection.textColor = [UIColor redColor];
        self.buySellDirection.text = [NSString stringWithFormat:@"看涨%d手",_currentModel.Qty];
        self.indicatorView.backgroundColor = [UIColor redColor];
    }else{
        self.buySellDirection.textColor = [UIColor greenColor];
        self.buySellDirection.text = [NSString stringWithFormat:@"看跌%d手",_currentModel.Qty*-1];
        self.indicatorView.backgroundColor = [UIColor greenColor];
    }
    
    if (_currentModel.UnrealizedPL < 0) {
        NSString *str = [NSString stringWithFormat:@"%.2f 元",_currentModel.UnrealizedPL];
        self.profit.attributedText = [NSString stringWithaString:str bigFont:15 smallFont:0 color:[UIColor greenColor]];
    }else if (_currentModel.UnrealizedPL > 0){
        NSString *str = [NSString stringWithFormat:@"+%.2f 元",_currentModel.UnrealizedPL];
        self.profit.attributedText = [NSString stringWithaString:str bigFont:15 smallFont:0 color:[UIColor redColor]];
    }else{
        NSString *str = [NSString stringWithFormat:@"+%.2f 元",_currentModel.UnrealizedPL];
        self.profit.attributedText = [NSString stringWithaString:str bigFont:15 smallFont:0 color:[UIColor whiteColor]];
    }
}

- (IBAction)clickOneKeyClose:(id)sender {
    if (!GLOBAL_ISLOGIN) {
        [self.view makeToast:@"请登录"];
        return;
    }
    
    
    if ([_currentModel.BuySell containsString:@"买"]) {  // 卖出操作
        
        [SVProgressHUD show];
        
        [OrderViewModel requestSendOrderBuysell:@"卖出" qty:abs(_currentModel.Qty) block:^(id obj) {
            [SVProgressHUD dismiss];
            [self.view makeToast:@"下单成功"];
        }];
    }else{  // 买入操作
        [SVProgressHUD show];
        
        [OrderViewModel requestSendOrderBuysell:@"买入" qty:abs(_currentModel.Qty) block:^(id obj) {
            [SVProgressHUD dismiss];
            [self.view makeToast:@"下单成功"];
        }];
    }
    
}

- (IBAction)clickRaise:(id)sender {
    if (!GLOBAL_ISLOGIN) {
        [SVProgressHUD showInfoWithStatus:@"请登录"];
        return;
    }
    
    QuickOrderModel *model = [[QuickOrderModel alloc] unarchiveObjectWithFileName:[Global shareInstance].quoteModel.Symbolname];
    
    if (model) {  // 有配置快速下单
        [SVProgressHUD show];
        [OrderViewModel requestSendOrderBuysell:@"买入" qty:model.qty block:^(id obj) {
            [SVProgressHUD dismiss];
            [self.view makeToast:@"下单成功"];
        }];
    }else{
        [self performSegueWithIdentifier:@"BuyOrder" sender:@"1"];
    }
    
}

- (IBAction)clickFall:(id)sender {
    if (!GLOBAL_ISLOGIN) {
        [SVProgressHUD showInfoWithStatus:@"请登录"];
        return;
    }
    
    QuickOrderModel *model = [[QuickOrderModel alloc] unarchiveObjectWithFileName:[Global shareInstance].quoteModel.Symbolname];
    
    if (model) {  // 有配置快速下单
        [SVProgressHUD show];
        [OrderViewModel requestSendOrderBuysell:@"卖出" qty:model.qty block:^(id obj) {
            [SVProgressHUD dismiss];
            [self.view makeToast:@"下单成功"];
        }];
    }else{
        [self performSegueWithIdentifier:@"SellOrderViewController" sender:@"2"];
    }
    
}


- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addPageTitleView:(NSString *)thirdTitle
{
    CGRect frame = CGRectMake(0, MaxY(self.orderDetailView.frame), SCREEN_WIDTH, kPageTitleViewH);
    
    NSArray *array = @[@"闪电图",@"分时图",thirdTitle,@"盘口"];
    
    self.pageTitleView = [[PageTitleView alloc] initWithFrame:frame titles:array isScrollEnable:NO];
    
    self.pageTitleView.delegate = self;
    
    [self.view addSubview:_pageTitleView];
}

- (void)addPageContentView
{
    NSArray *chartVcs = @[NSStringFromClass([LightningViewController class]),
                          NSStringFromClass([TimeViewController class]),
                          NSStringFromClass([KlineViewController class]),
                          NSStringFromClass([MarketViewController class])];
    
    NSMutableArray *vcArry = [NSMutableArray array];
    
    [chartVcs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIViewController *vc = [[NSClassFromString(obj) alloc] init];
        vc.view.backgroundColor = [UIColor randomColor];
        [vcArry addObject:vc];
    }];
    
    CGRect frame = CGRectMake(0, MaxY(self.orderDetailView.frame) + kPageTitleViewH, SCREEN_WIDTH, kPageContentViewH);
    
    _pageContentView = [[PageContentView alloc] initWithFrame:frame childViewControllers:vcArry parentViewController:self];
    
    _pageContentView.delegate = self;
    
    [self.view addSubview:_pageContentView];
}

- (void)addKlineDrop{
    ZFDropDown * dropDown = [[ZFDropDown alloc] initWithFrame:CGRectMake(15*2+12+64*2,MaxY(self.orderDetailView.frame) + 10,75,30) pattern:kDropDownPatternDefault];
    dropDown.delegate = self;
//    [dropDown.topicButton setTitle:@"Please choose 1 continent / area" forState:UIControlStateNormal];
    [self.view addSubview:dropDown];
    _dropDown = dropDown;
//    [dropDown mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.pageTitleView.mas_bottom);
//        make.height.equalTo(@100);
//        make.width.equalTo(@100);
//        make.left.mas_equalTo(@(15*2+12+64*2));
//    }];
}

- (NSArray *)itemArrayInDropDown:(ZFDropDown *)dropDown{
    _klineArray = @[@"1分钟", @"5分钟", @"15分钟",@"60分钟", @"1日"];
    return _klineArray;
}

- (void)dropDown:(ZFDropDown *)dropDown didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.pageTitleView) {
        [self.pageTitleView removeFromSuperview];
        NSString *str = [NSString stringWithFormat:@"%@ ↓",_klineArray[indexPath.row]];
        [self addPageTitleView:str];
        [_dropDown removeFromSuperview];
        [self addKlineDrop];
        [self didSelectTitleView:self.pageTitleView index:2];
        [self didScrollPageContentView:self.pageContentView sourceIndex:1 targetIndex:2 progress:0];
    }
    MYLog(@"%ld",(long)indexPath.row);
    // 通知KlineView点击了K线类型
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SelectedKlineType" object:@(indexPath.row)];
}

- (void)scrollEnable:(BOOL)enable{
    [_pageContentView scrollEnabled:enable];
}

- (void)didSelectTitleView:(PageTitleView *)pageTitleView index:(int)index
{
    [_pageContentView scrollToIndex:index];
}

- (void)didScrollPageContentView:(PageContentView *)pageContentView sourceIndex:(int)sourceIndex targetIndex:(int)targetIndex progress:(CGFloat)progress
{
    [_pageTitleView setCurrentTitleSourceIndex:sourceIndex targetIndex:targetIndex progress:progress];
}





- (IBAction)clickRegister:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Profile" bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"RegisterViewController"];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (IBAction)clickLogin:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Profile" bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:[BuyOrderViewController class]]) {
        UITableViewController *vc = segue.destinationViewController;
        vc.title = @"买入委托";
    }
}

- (void)updateUI{
    self.buyPrice.text = NSStringFromDouble(_quoteModel.AskPrice);
    self.sellPrice.text = NSStringFromDouble(_quoteModel.BidPrice);
    self.buyVolume.text = NSStringFromInt(_quoteModel.askSize);
    self.sellVolume.text = NSStringFromInt(_quoteModel.BidSize);
    self.lastPrice.text = NSStringFromFloat(_quoteModel.LastPrice);
    self.change.text = NSStringFromFloat(_quoteModel.Change);
    self.changeRate.text = [NSStringFromFloat(_quoteModel.ChangeRate) stringByAppendingString:@"%"];
    
    float ask = _quoteModel.askSize;
    float bid = _quoteModel.BidSize;
    
    if (!ask*bid) return;  // 为0时返回
    
    float all = ask + bid;
    
    CGFloat askW = ask/all*80;
    CGFloat bidW = bid/all*80;
    
    if (isnan(askW)||isnan(bidW)) return;
    
    [UIView animateWithDuration:0.2 animations:^{
        self.buyViewWidth.constant = askW;
        self.sellViewWidth.constant = bidW;
        [self.view layoutIfNeeded];
    }];
    
}


@end
